var e = require;
var t = module;
var n = exports;
var _ =
        (this && this.__awaiter) ||
        function (e, a, s, c) {
            return new (s = s || Promise)(function (n, t) {
                function o(e) {
                    try {
                        r(c.next(e));
                    } catch (e) {
                        t(e);
                    }
                }
                function i(e) {
                    try {
                        r(c.throw(e));
                    } catch (e) {
                        t(e);
                    }
                }
                function r(e) {
                    var t;
                    e.done
                        ? n(e.value)
                        : ((t = e.value) instanceof s
                              ? t
                              : new s(function (e) {
                                    e(t);
                                })
                          ).then(o, i);
                }
                r((c = c.apply(e, a || [])).next());
            });
        },
    w =
        (this && this.__generator) ||
        function (n, o) {
            var i,
                r,
                a,
                s = {
                    label: 0,
                    sent: function () {
                        if (1 & a[0]) throw a[1];
                        return a[1];
                    },
                    trys: [],
                    ops: []
                },
                e = {next: t(0), throw: t(1), return: t(2)};
            return (
                "function" == typeof Symbol &&
                    (e[Symbol.iterator] = function () {
                        return this;
                    }),
                e
            );
            function t(t) {
                return function (e) {
                    return (function (t) {
                        if (i) throw new TypeError("Generator is already executing.");
                        for (; s; )
                            try {
                                if (
                                    ((i = 1),
                                    r &&
                                        (a =
                                            2 & t[0]
                                                ? r.return
                                                : t[0]
                                                ? r.throw || ((a = r.return) && a.call(r), 0)
                                                : r.next) &&
                                        !(a = a.call(r, t[1])).done)
                                )
                                    return a;
                                switch (((r = 0), (t = a ? [2 & t[0], a.value] : t)[0])) {
                                    case 0:
                                    case 1:
                                        a = t;
                                        break;
                                    case 4:
                                        return s.label++, {value: t[1], done: !1};
                                    case 5:
                                        s.label++, (r = t[1]), (t = [0]);
                                        continue;
                                    case 7:
                                        (t = s.ops.pop()), s.trys.pop();
                                        continue;
                                    default:
                                        if (
                                            !(a = 0 < (a = s.trys).length && a[a.length - 1]) &&
                                            (6 === t[0] || 2 === t[0])
                                        ) {
                                            s = 0;
                                            continue;
                                        }
                                        if (3 === t[0] && (!a || (t[1] > a[0] && t[1] < a[3]))) {
                                            s.label = t[1];
                                            break;
                                        }
                                        if (6 === t[0] && s.label < a[1]) {
                                            (s.label = a[1]), (a = t);
                                            break;
                                        }
                                        if (a && s.label < a[2]) {
                                            (s.label = a[2]), s.ops.push(t);
                                            break;
                                        }
                                        a[2] && s.ops.pop(), s.trys.pop();
                                        continue;
                                }
                                t = o.call(n, s);
                            } catch (e) {
                                (t = [6, e]), (r = 0);
                            } finally {
                                i = a = 0;
                            }
                        if (5 & t[0]) throw t[1];
                        return {value: t[0] ? t[1] : void 0, done: !0};
                    })([t, e]);
                };
            }
        };
Object.defineProperty(n, "__esModule", {value: !0}), (n.post = n.get = n.makeRequest = void 0);
var C = e("index"),
    k = e("common"),
    S = e("env"),
    o = e("toast"),
    I = e("user-data"),
    T = {ignoreCache: !1, headers: {Accept: "application/json, text/javascript, text/plain"}, timeout: 5e3},
    O = 0;
function N(e, t) {
    var n,
        t =
            null == (n = t)
                ? ""
                : Object.keys(n)
                      .map(function (e) {
                          return encodeURIComponent(e) + "=" + encodeURIComponent(n[e] + "");
                      })
                      .join("&");
    return 0 < t.length ? e + (-1 === e.indexOf("?") ? "?" : "&") + t : e;
}
function D(t) {
    var e,
        n = {ok: 200 <= t.status && t.status < 300, status: t.status, statusText: t.statusText, data: t.responseText};
    if (n.ok)
        try {
            var o = JSON.parse(t.responseText);
            null != o.errcode &&
                0 < o.errcode &&
                ((n.ok = !1),
                (n.status = o.errcode),
                (n.statusText = null !== (e = o.errmsg) && void 0 !== e ? e : n.statusText)),
                (n.data = o.data);
        } catch (e) {
            console.error("failed to parse response text", t.responseText, e);
        }
    return n;
}
function i(y, g, v) {
    var b;
    return _(this, void 0, Promise, function () {
        var t, n, o, u, p, h, d, f, m;
        return w(this, function (e) {
            switch (e.label) {
                case 0:
                    ((v = null != v ? v : {}).parameters = null !== (b = v.parameters) && void 0 !== b ? b : {}),
                        (v.parameters.consistKey = O++),
                        (n = function () {
                            v.silence ||
                                (t = setTimeout(function () {
                                    C.platform.showLoading();
                                }, 200));
                        }),
                        (o = function () {
                            null != t && (clearTimeout(t), C.platform.hideLoading());
                        }),
                        (u = null == v.askToRetry || 1 == v.askToRetry),
                        (p = Math.max(
                            1,
                            null !== (b = v.maxAutoRetryCnt) && void 0 !== b ? b : S.env.network.defaultRetryCnt
                        )),
                        (h = 0),
                        (e.label = 1);
                case 1:
                    if (!(h < p || u)) return [3, 11];
                    e.label = 2;
                case 2:
                    return (
                        e.trys.push([2, 4, , 10]),
                        n(),
                        [
                            4,
                            ((i = y),
                            (r = g),
                            (a = v),
                            (s = T.ignoreCache),
                            (c = T.headers),
                            (l = T.timeout),
                            new Promise(function (e, t) {
                                var n = new XMLHttpRequest(),
                                    o = N(r, {
                                        platform: C.platform.string(),
                                        ver: S.env.version,
                                        uid: I.userData.basic.uid
                                    });
                                a && (o = N(o, a.parameters)),
                                    n.open(i, o),
                                    c &&
                                        Object.keys(c).forEach(function (e) {
                                            n.setRequestHeader(e, c[e]);
                                        }),
                                    s && n.setRequestHeader("Cache-Control", "no-cache"),
                                    (n.timeout = l),
                                    (n.onload = function () {
                                        e(D(n));
                                    }),
                                    (n.onerror = function () {
                                        e(D(n));
                                    }),
                                    (n.ontimeout = function () {
                                        t(new Error("Time out"));
                                    }),
                                    "post" === i && a.body
                                        ? (n.setRequestHeader("Content-Type", "application/json"),
                                          n.send(JSON.stringify(a.body)))
                                        : n.send();
                            }))
                        ]
                    );
                case 3:
                    if (((d = e.sent()), o(), (200 <= d.status && d.status <= 399) || 2e4 <= d.status)) return [2, d];
                    throw d;
                case 4:
                    if (((f = e.sent()), o(), !v.silence)) return [3, 6];
                    if (h == p - 1) throw f;
                    return [4, k.sleep(0.5)];
                case 5:
                    return e.sent(), [3, 9];
                case 6:
                    return (m = !u)
                        ? [3, 8]
                        : [
                              4,
                              (function () {
                                  return _(this, void 0, Promise, function () {
                                      return w(this, function (e) {
                                          switch (e.label) {
                                              case 0:
                                                  return [
                                                      4,
                                                      C.platform.showModal({
                                                          title: "提示",
                                                          content: "网络发生故障, 是否重试？",
                                                          confirmText: "重试",
                                                          cancelText: "取消",
                                                          showClose: !1
                                                      })
                                                  ];
                                              case 1:
                                                  return [2, e.sent()];
                                          }
                                      });
                                  });
                              })()
                          ];
                case 7:
                    (m = !e.sent()), (e.label = 8);
                case 8:
                    if (m) throw f;
                    e.label = 9;
                case 9:
                    return [3, 10];
                case 10:
                    return h++, [3, 1];
                case 11:
                    return [2];
            }
            var i, r, a, s, c, l;
        });
    });
}
n.makeRequest = i;
var e =
        ((s.prototype.isEmpty = function () {
            return 0 == this.queue.length;
        }),
        (s.prototype.push = function (e) {
            e.request = e.request || {};
            var t = this.isEmpty();
            this.queue.push(e), t && this.consume();
        }),
        (s.prototype.clear = function () {
            for (; !this.isEmpty(); )
                this.queue.pop().onFailed(new Error("the queue of " + this.method + " was cleared"));
        }),
        (s.prototype.handleError = function (e, t) {
            console.log("handle error", t),
                t instanceof Error ? e.onFailed(t) : e.onFailed(new Error(t.statusText)),
                e.request.silence ||
                    (t instanceof Error
                        ? o.showToast(t.message)
                        : t.statusText
                        ? o.showToast(t.statusText)
                        : o.showToast("网络请求失败"));
        }),
        (s.prototype.consume = function () {
            return _(this, void 0, void 0, function () {
                var t, n;
                return w(this, function (e) {
                    switch (e.label) {
                        case 0:
                            (t = this.queue[0]), (e.label = 1);
                        case 1:
                            return (
                                e.trys.push([1, 3, , 4]), [4, i(this.method, S.env.network.server + t.url, t.request)]
                            );
                        case 2:
                            return (n = e.sent()).ok ? t.onSuccess(n) : this.handleError(t, n), [3, 4];
                        case 3:
                            return (n = e.sent()), this.handleError(t, n), [3, 4];
                        case 4:
                            return this.queue.shift(), this.isEmpty() || this.consume(), [2];
                    }
                });
            });
        }),
        s),
    r = new e("get"),
    a = new e("post");
function s(e) {
    (this.method = e), (this.queue = []);
}
(n.get = function (e, o) {
    return _(this, void 0, Promise, function () {
        return w(this, function () {
            return [
                2,
                new Promise(function (t, n) {
                    r.push({
                        request: o,
                        url: e,
                        onSuccess: function (e) {
                            t(e);
                        },
                        onFailed: function (e) {
                            o.safe ? t({data: null, ok: !1, status: -1, statusText: e.message}) : n(e);
                        }
                    });
                })
            ];
        });
    });
}),
    (n.post = function (e, o) {
        return _(this, void 0, Promise, function () {
            return w(this, function () {
                return [
                    2,
                    new Promise(function (t, n) {
                        a.push({
                            url: e,
                            request: o,
                            onSuccess: function (e) {
                                t(e);
                            },
                            onFailed: function (e) {
                                o.safe ? t({data: null, ok: !1, status: -1, statusText: e.message}) : n(e);
                            }
                        });
                    })
                ];
            });
        });
    });
